// 实现这个项目的构建任务

const { src, dest, parallel, series, watch } = require('gulp')
const sass = require('gulp-sass')
const babel = require('gulp-babel')
const htmlmin = require('gulp-htmlmin')
const swig = require('gulp-swig')
const imagemin = require('gulp-imagemin')
const del = require('del')
const bs = require('browser-sync')

const data = {
    menus: [
        {
            name: 'Home',
            icon: 'aperture',
            link: 'index.html'
        },
        {
            name: 'Features',
            link: 'features.html'
        },
        {
            name: 'About',
            link: 'about.html'
        },
        {
            name: 'Contact',
            link: '#',
            children: [
            {
                name: 'Twitter',
                link: 'https://twitter.com/w_zce'
            },
            {
                name: 'About',
                link: 'https://weibo.com/zceme'
            },
            {
                name: 'divider'
            },
            {
                name: 'About',
                link: 'https://github.com/zce'
            }
            ]
        }
    ],
    pkg: require('./package.json'),
    date: new Date()
}

const clean = () => {
    return del('dist')
}

const style = () => {
    return src('src/**/*.scss', { base: 'src' })
        .pipe(sass())
        .pipe(dest('dist'))
        .pipe(bs.reload({ stream: true }))
}

const scripts = () => {
    return src('src/**/*.js', { base: 'src' })
        .pipe(babel())
        .pipe(dest('dist'))
        .pipe(bs.reload({ stream: true }))
}

const pages = () => {
    return src('src/**/*.html', { base: 'src' })
        .pipe(swig({ data }))
        .pipe(dest('dist'))
        .pipe(bs.reload({ stream: true }))
}

const images = () => {
    return src('src/assets/images/**', { base: 'src' })
        .pipe(imagemin())
        .pipe(dest('dist'))
        .pipe(bs.reload({ stream: true }))
}

const fonts = () => {
    return src('src/assets/fonts/**', { base: 'src' })
        .pipe(imagemin())
        .pipe(dest('dist'))
        .pipe(bs.reload({ stream: true }))
}

const extra = () => {
    return src('public/**', { base: 'public' })
        .pipe(dest('dist'))
        .pipe(bs.reload({ stream: true }))
}

const serve = () => {
    watch('src/**/*.scss', style)
    watch('src/**/*.js', scripts)
    watch('src/**/*.html', pages)
    watch('src/assets/images/**', images)
    watch('src/assets/fonts/**', fonts)
    watch('public/**', extra)
    bs.init({
        notify: false,
        open: true,
        port: 3000,
        server: {
            baseDir: ['dist', 'src', 'public'],
            routes: {
                '/node_modules': 'node_modules'
            }
        }
    })
}

const compile = series(clean, parallel(style, scripts, pages, images, fonts))
const build = series(clean, parallel(compile, extra))

module.exports = {
    compile,
    build,
    serve
}